package com.cbgolf.oa.views;

import android.app.Activity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.cbgolf.oa.R;
import com.cbgolf.oa.base.BaseViewNew;
import com.cbgolf.oa.contract.ICloseParkContract;
import com.cbgolf.oa.entity.Beans;
import com.cbgolf.oa.event.Events;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.manager.DialogManager;
import com.cbgolf.oa.manager.DialogManager.IDialogManagerWaiter;
import com.cbgolf.oa.util.AnimaUtil;
import com.cbgolf.oa.util.DateUtil;
import com.cbgolf.oa.util.EnumUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.util.ViewUtils;
import com.cbgolf.oa.widget.TopView;
import com.cbgolf.oa.widget.pickview.view.OptionsPickerView;
import com.cbgolf.oa.widget.pickview.view.TimePickerView;
import com.cbgolf.oa.widget.pickview.view.TimePickerView.Type;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

/**
 * @author lq
 */
public class AddCloseParkViewImp extends BaseViewNew implements ICloseParkContract.View {

  @BindView(R.id.topView)
  TopView topView;

  @BindView(R.id.ll_closepark_cause)
  View causeView;
  @BindView(R.id.tv_closepark_cause)
  TextView causeTv;
  @BindView(R.id.ll_closepark_starttime)
  View startTimeView;
  @BindView(R.id.tv_closepark_starttime)
  TextView startTimeTv;
  @BindView(R.id.ll_closepark_endtime)
  View endTimeView;
  @BindView(R.id.tv_closepark_endtime)
  TextView endTimeTv;

  @BindView(R.id.et_closepark_msg)
  EditText msgEt;
  @BindView(R.id.tv_closepark_submit)
  TextView submitTv;

  private OptionsPickerView pvOptions;
  private TimePickerView pvTimeStart;
  private TimePickerView pvTimeEnd;
  private ArrayList<Beans> listCause = new ArrayList<>();

  private ICloseParkContract.Waiter worker;
  private int mType;
  private Beans mData;
  private long startTime;
  private long endTime;
  private boolean isEdit;
  private String causeType;


  public AddCloseParkViewImp(Activity act, ICloseParkContract.Waiter waiter, int type, Beans data) {
    this.worker = waiter;
    this.mData = data;
    this.mType = type;
    ButterKnife.bind(this, act);
    super.init(act);
  }

  @Override
  protected void setViews() {
    topView.setTitle(worker.getActivityTitle());

    showViewType();
    initOptions();
    initTimePv();
//    initTimeOptions();

  }

  private void showViewType() {
    if (mType == EnumUtil.CLOSE_PARK_SHOW_DETAILS) {
      causeView.setEnabled(false);
      startTimeView.setEnabled(false);
      endTimeView.setEnabled(false);
      msgEt.setEnabled(false);
      if (null != mData) {
        ViewUtils.setText(causeTv, EnumUtil.getCloseParkCause(mData.reason));
        ViewUtils.setText(startTimeTv, DateUtil.stampToDate(mData.startTime, DateUtil.formatYMDHm));
        ViewUtils.setText(endTimeTv, DateUtil.stampToDate(mData.endTime, DateUtil.formatYMDHm));
        ViewUtils.setText(msgEt, mData.remark);
        ViewUtils.setText(submitTv, "取消封场");
        startTime = mData.startTime;
        endTime = mData.endTime;
        causeType = TextUtil.Text(mData.reason, "OTHER");
        topView.setTopRightTvVisible(true);
        topView.setRightTvText("编辑");
        if (!mData.closured) {
          topView.setTopRightTvVisible(false);
          ViewUtils.setVisible(submitTv, false);
        }
      }
    }
  }


  private void initTimePv() {
    // 时间选择器
    pvTimeStart = new TimePickerView(context, Type.ALL);
    // 控制时间范围
    final Calendar calendar = Calendar.getInstance();
    pvTimeStart.setRange(calendar.get(Calendar.YEAR),
        calendar.get(Calendar.YEAR) + 20);
    pvTimeStart.setTime(startTime > 0 ? new Date(startTime) : new Date());
    pvTimeStart.setPickerBackgroudColor(R.color.white);
    pvTimeStart.setCyclic(false);
    pvTimeStart.setCancelable(true);
    pvTimeStart.setTitle("封场开始时间");

    // 时间选择器
    pvTimeEnd = new TimePickerView(context, Type.ALL);
    // 控制时间范围
    pvTimeEnd.setRange(calendar.get(Calendar.YEAR),
        calendar.get(Calendar.YEAR) + 20);
    pvTimeEnd.setTime(endTime > 0 ? new Date(endTime) :
        (startTime > 0 ? new Date(startTime) : new Date()));
    pvTimeEnd.setPickerBackgroudColor(R.color.white);
    pvTimeEnd.setCyclic(false);
    pvTimeEnd.setTitle("封场结束时间");
    pvTimeEnd.setCancelable(true);
  }

  private void initOptions() {
    String[] causeTypes = new String[]{
        "COMPETITION",
        "ACTIVITY",
        "MAINTAIN",
        "CLOSED",
        "OTHER",
    };
    String[] causeTexts = new String[]{
        "比赛封场",
        "活动封场",
        "养护封场",
        "闭场封场",
        "其他封场"
    };
    Beans beans;
    for (int i = 0; i < causeTexts.length; i++) {
      beans = new Beans();
      beans.causeName = causeTexts[i];
      beans.reason = causeTypes[i];
      listCause.add(beans);
    }
    pvOptions = new OptionsPickerView(context);
    pvOptions.setPicker(listCause);
    pvOptions.setLabels(null);
    pvOptions.setCyclic(false);
    pvOptions.setCancelable(true);
    pvOptions.setSelectOptions(1);
    pvOptions.setTitle(context.getString(R.string.close_park_cause_chose));
  }

  @Override
  protected void setListener() {
    topView.setBackListener(v -> worker.back());
    ViewUtils.setClick(causeView, v -> {
      if (isEdit && startTime <= System.currentTimeMillis()) {
        Util.show("封场已开始，原因无法编辑");
        return;
      }
      if (isEdit && endTime <= System.currentTimeMillis()) {
        Util.show("封场已结束，无法编辑");
        return;
      }
      pvOptions.show();
    });
    pvOptions.setOnoptionsSelectListener(
        (options1, option2, options3) -> {
          ViewUtils
              .setText(causeTv, listCause.get(options1).getPickerViewText());
          causeType = listCause.get(options1).reason;
        });
    ViewUtils.setClick(startTimeView, v -> {
      if (isEdit && startTime <= System.currentTimeMillis()) {
        Util.show("开始时间已生效，无法编辑");
        return;
      }
      pvTimeStart.show();
    });
    ViewUtils.setClick(endTimeView, v ->
    {
      if (isEdit && endTime <= System.currentTimeMillis()) {
        Util.show("封场已结束，无法编辑");
        return;
      }
      pvTimeEnd.show();
    });
    // 时间选择后回调
    pvTimeStart.setOnTimeSelectListener(
        date -> {
          startTime = date.getTime();
          Log.e("startTime---------", DateUtil.stampToDate(startTime));
          ViewUtils
              .setText(startTimeTv, DateUtil.stampToDate(date.getTime(), DateUtil.formatYMDHm));
        });
    pvTimeEnd.setOnTimeSelectListener(
        date -> {
          endTime = date.getTime();
          Log.e("endTime---------", DateUtil.stampToDate(endTime));
          ViewUtils
              .setText(endTimeTv, DateUtil.stampToDate(date.getTime(), DateUtil.formatYMDHm));
        });
    ViewUtils.setClick(submitTv, v -> {
          if (TextUtil.contains(submitTv.getText().toString(),
              context.getString(R.string.cancel))) {
            DialogManager.getInstance().showMsgDialog(context,
                context.getString(R.string.close_park_cancel_tip),
                context.getString(R.string.are_you_sure_cancel_close_park),
                new IDialogManagerWaiter() {
                  @Override
                  public void doSubmit() {
                    worker.cancelClosePark(null != mData ? mData.id : "");
                  }

                  @Override
                  public void doCancel() {

                  }
                });
          } else {
            checkInfos();
          }
        }
    );
    topView.setTopRightTvListener(v -> {
      ViewUtils.setEnable(causeView, true);
      ViewUtils.setEnable(startTimeView, true);
      ViewUtils.setEnable(endTimeView, true);
      ViewUtils.setEnable(msgEt, true);
      ViewUtils.setText(submitTv, "保存");
      isEdit = true;
      topView.setTopRightTvVisible(false);
    });
  }

  private void checkInfos() {
    String cause = causeTv.getText().toString();
    if (Util.isNull(causeType)) {
      Util.show("请输入封场名称");
      return;
    }
    if (startTime <= 0) {
      Util.show("请选择开始时间");
      return;
    }
    if (!isEdit && startTime < System.currentTimeMillis()) {
      Util.show("开始时间应大于当前时间");
      return;
    }
    if (endTime <= 0) {
      Util.show("请选择结束时间");
      return;
    }
    if (endTime <= startTime) {
      Util.show("结束时间应大于开始时间");
      return;
    }
    if (!isEdit && endTime < System.currentTimeMillis()) {
      Util.show("结束时间应大于当前时间");
      return;
    }
    Beans beans = new Beans();
    beans.startTime = startTime;
    beans.endTime = endTime;
    beans.causeName = cause;
    beans.reason = TextUtil.Text(causeType, "OTHER");
    beans.remark = msgEt.getText().toString();
    beans.isEdit = isEdit;
    beans.id = (null != mData ? mData.id : "");
    worker.addClosePark(beans);

  }

  @Override
  public void showProgress() {
    AnimaUtil.showLoading(context, false);
  }

  @Override
  public void stopProgress() {
    AnimaUtil.stopLoading();
  }

  @Override
  public void requestFail(String msg, int code) {
    Util.show(msg);
  }

  @Override
  public void requestOver(Events event) {
    if (null == event) {
      return;
    }
    switch (event.msgTarget) {
      case DataManager.CLOSE_PARK_CANCEL:
        stopProgress();
        if (event.isSuccess) {
          worker.cancelSuccess();
        } else {
          Util.show(Util.isNull(event.errorMsg) ? ErrorUtil.NETERROR : event.errorMsg);
        }
        break;
      case DataManager.CLOSE_PARK_CREATE:
      case DataManager.CLOSE_PARK_EDIT:
        stopProgress();
        if (event.isSuccess) {
          worker.addSuccess();
        } else {
          Util.show(Util.isNull(event.errorMsg) ? ErrorUtil.NETERROR : event.errorMsg);
        }
        break;
      default:
        break;
    }

  }


}
